//
//  ViewController.m
//  NSURLSessionDemo
//
//  Created by liy on 2024/10/15.
//https://blog.csdn.net/potato512/article/details/43988155
//NSURLSession使用

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) UIImageView *imageview;
@property (nonatomic, strong) NSMutableURLRequest *mutableRequest;
@property (nonatomic, strong) NSURLSessionDataTask *dataTask;
@property (nonatomic, strong) NSURLSessionDataTask *imageDataTask;
@property (nonatomic, strong) NSMutableData *networkData;
@property (nonatomic, strong) NSMutableData *imageData;
@property (nonatomic, strong) NSMutableDictionary *networkDict;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  [self setupData];
//  [self useSessionByDelegate];
  [self useSessionByBlock];
}

- (void)setupData {
  self.networkData = [NSMutableData data];
  self.imageData = [NSMutableData data];

  self.networkDict = [NSMutableDictionary dictionary];
}

//使用block方式创建session
- (void)useSessionByBlock {
  // 创建NSURLSession
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
  // 创建NSURLRequest
  // 图片地址
  // NSString *string = @"http://img4.imgtn.bdimg.com/it/u=819265564,3078214620&fm=206&gp=0.jpg";
  // 天气地址
  NSString *string = @"http://api.k780.com:88/?app=weather.future&weaid=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";

  string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];       // 请求地址中包含中文时进行转换
  NSURL *url = [NSURL URLWithString:string];
  NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
  // 缓存
  mutableRequest.cachePolicy = NSURLRequestUseProtocolCachePolicy;
  // 请求超时
  mutableRequest.timeoutInterval = 30.0;
  // 请求方式POST、或GET
  // mutableRequest.HTTPMethod = @"POST";
  mutableRequest.HTTPMethod = @"GET";

  // 创建NSURLSessionDataTask
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mutableRequest
                                              completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
    UIImage *image = [UIImage imageWithData:data];
    self.imageview.image = image;
  }];

  // 开始网络请求
  [dataTask resume];
  // 停止请求网络
//  [dataTask cancel];
//
//  // 取消/关闭NSURLSession
//  [session finishTasksAndInvalidate];
}

//使用代理方式创建session
- (void)useSessionByDelegate {
  // 创建NSURLSession
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:queue];

  // 创建NSURLRequest
  // 图片地址
  // NSString *string = @"http://img4.imgtn.bdimg.com/it/u=819265564,3078214620&fm=206&gp=0.jpg";
  // 天气地址
  NSString *string = @"http://api.k780.com:88/?app=weather.future&weaid=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";

  string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];             // 请求地址中包含中文时进行转换
  NSURL *url = [NSURL URLWithString:string];
  NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
  // 缓存
  mutableRequest.cachePolicy = NSURLRequestUseProtocolCachePolicy;
  // 请求超时
  mutableRequest.timeoutInterval = 30.0;
  // 请求方式POST、或GET
  // mutableRequest.HTTPMethod = @"POST";
  mutableRequest.HTTPMethod = @"GET";
  self.mutableRequest = mutableRequest;

  // 创建NSURLSessionDataTask
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:self.mutableRequest];
  self.dataTask = dataTask;
  // 开始网络请求
  [dataTask resume];
  // 停止请求网络
//  [dataTask cancel];

  // 取消/关闭NSURLSession
//  [session finishTasksAndInvalidate];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
  NSLog(@"1 请求成功返回请求头信息 response = %@", response);

  // 让任务继续正常进行.(如果没有写这行代码, 将不会执行下面的代理方法.)
  completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  NSLog(@"2 请求成功返回接收到的信息 data = %@", data);

  if (0 != data.length) {
    if (dataTask == self.dataTask) {
      [self.networkData appendData:data];
    } else if (dataTask == self.imageDataTask) {
      if (self.imageData == nil) {
        self.imageData = [[NSMutableData alloc] init];
      }

      [self.imageData appendData:data];
    }
  }
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
  NSLog(@"3 请求成功结束请求");

  NSString *result = [[NSString alloc] initWithData:self.networkData encoding:NSUTF8StringEncoding];
  NSLog(@"result = %@", result);

  if (task == self.dataTask) {
    self.networkDict = [NSJSONSerialization JSONObjectWithData:self.networkData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"resultDict = %@", self.networkDict);

    if (self.networkDict && 0 != self.networkDict.count) {
      [self.tableview reloadData];
    }
  } else if (task == self.imageDataTask) {
    UIImage *image = [UIImage imageWithData:self.imageData];
    self.imageview.image = image;
  }
}

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
{
  NSLog(@"4 请求失败");
}

@end
